#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
提取Kuga正确的catalogId脚本
访问Kuga配置器页面，提取正确的catalogId和配置信息
"""

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager
import time
import re
import json
from datetime import datetime


def extract_kuga_catalog_info():
    """提取Kuga的catalog信息"""
    print("🔍 正在提取Kuga的正确catalogId...")
    
    # Chrome配置
    chrome_options = Options()
    chrome_options.add_argument('--headless')
    chrome_options.add_argument('--no-sandbox')
    chrome_options.add_argument('--disable-dev-shm-usage')
    chrome_options.add_argument('--disable-gpu')
    chrome_options.add_argument('--window-size=1920,1080')
    chrome_options.add_argument('--user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36')
    
    # 初始化driver
    service = Service(ChromeDriverManager().install())
    driver = webdriver.Chrome(service=service, options=chrome_options)
    
    try:
        # 首先访问Kuga页面
        kuga_url = "https://www.ford.co.uk/cars/kuga"
        print(f"📄 访问Kuga页面: {kuga_url}")
        driver.get(kuga_url)
        time.sleep(3)
        
        # 查找配置器链接
        configurator_links = []
        try:
            # 查找"Build & Price"或类似的链接
            links = driver.find_elements(By.TAG_NAME, "a")
            for link in links:
                href = link.get_attribute("href")
                text = link.text.strip().lower()
                if href and ("build" in text or "configure" in text or "price" in text):
                    if "ford.co.uk" in href and ("mec" in href or "ngc2" in href):
                        configurator_links.append({
                            "text": text,
                            "url": href
                        })
                        print(f"🔗 找到配置器链接: {text} -> {href}")
        except Exception as e:
            print(f"⚠️ 查找配置器链接失败: {e}")
        
        # 如果找到配置器链接，访问第一个
        catalog_info = {}
        if configurator_links:
            config_url = configurator_links[0]["url"]
            print(f"🔧 访问配置器页面: {config_url}")
            driver.get(config_url)
            time.sleep(5)
            
            # 从URL中提取catalogId
            catalog_match = re.search(r'catalogId=([^&]+)', config_url)
            if catalog_match:
                catalog_id = catalog_match.group(1)
                print(f"✅ 从URL提取catalogId: {catalog_id}")
                catalog_info["catalog_id"] = catalog_id
                catalog_info["configurator_url"] = config_url
            
            # 尝试从页面源码中提取更多信息
            try:
                page_source = driver.page_source
                
                # 查找可能的series codes或配置信息
                series_patterns = [
                    r'"seriesCode":\s*"([^"]+)"',
                    r'"series":\s*"([^"]+)"',
                    r'seriesCode=([^&\'"]+)',
                    r'series=([^&\'"]+)'
                ]
                
                series_codes = set()
                for pattern in series_patterns:
                    matches = re.findall(pattern, page_source)
                    series_codes.update(matches)
                
                if series_codes:
                    print(f"🔍 找到可能的series codes: {list(series_codes)}")
                    catalog_info["possible_series_codes"] = list(series_codes)
                
                # 查找车型配置名称
                config_patterns = [
                    r'"trim":\s*"([^"]+)"',
                    r'"grade":\s*"([^"]+)"',
                    r'data-trim="([^"]+)"',
                    r'data-grade="([^"]+)"'
                ]
                
                config_names = set()
                for pattern in config_patterns:
                    matches = re.findall(pattern, page_source)
                    config_names.update(matches)
                
                if config_names:
                    print(f"🎯 找到可能的配置名称: {list(config_names)}")
                    catalog_info["possible_trims"] = list(config_names)
                    
            except Exception as e:
                print(f"⚠️ 页面解析失败: {e}")
        
        else:
            print("❌ 未找到配置器链接")
        
        # 保存结果
        result = {
            "extraction_time": datetime.now().isoformat(),
            "model": "kuga",
            "kuga_page": kuga_url,
            "configurator_links": configurator_links,
            "catalog_info": catalog_info
        }
        
        output_file = "./release/kuga_catalog_extraction.json"
        with open(output_file, 'w', encoding='utf-8') as f:
            json.dump(result, f, indent=2, ensure_ascii=False)
        
        print(f"💾 结果已保存到: {output_file}")
        return catalog_info
        
    except Exception as e:
        print(f"❌ 提取失败: {e}")
        return {}
    finally:
        driver.quit()


if __name__ == "__main__":
    print("🚗 Kuga CatalogId 提取工具")
    print("=" * 50)
    
    catalog_info = extract_kuga_catalog_info()
    
    if catalog_info:
        print("\n✅ 提取完成!")
        print(f"📋 CatalogId: {catalog_info.get('catalog_id', 'N/A')}")
        print(f"🔗 配置器URL: {catalog_info.get('configurator_url', 'N/A')}")
    else:
        print("\n❌ 提取失败，请检查网络连接或页面结构变化")
